package user.Controller.borrowBook;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import user.utils.DBUitls;
import user.utils.JsonUntil;
import user.Model.service.Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/*
* 从前端获取书名的信息
* 进行借书的操作，修改书籍的状态由在馆到申请借阅中
* 返回完成的信息
* */
@WebServlet(name = "borrowBookServlet", value = "/user/borrowBookServlet")
public class borrowBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转化成String类
        String jsonString=String.valueOf(JsonUntil.getJson(req));
        //转换成JSONObject类
        JSONObject jsonObject= JSON.parseObject(jsonString);
        //获取书名
        String bookName = jsonObject.getString("bookName");
        //进行借书操作
        int count = 0;
        try {
            count = Service.borrowBook(bookName);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                DBUitls.freeConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //向前端返回值
        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();
        //如果返回值为0
        if (count == 0){
            object.put("code","-1");
            object.put("message","书籍借阅失败");
            out.println(object);
        }
        else{
            object.put("code","200");
            object.put("message","书籍借阅成功");
            object.put("userType","user");
            out.println(object);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
